<template>
  <div class="box">
    <!-- 头部搜索模块 -->
    <headerSearch :selectObj="selectObject" :isShowAdd="menuFlag" :goSearchFc="searchClick" :buttonList="buttonList" />
    <!-- 中间表格模块 -->
    <BaseTable :data="jobReporttableData" :columns="jobReportColumns" @details="selectDataList" :tableHeight="tableHeight"
      :pagination="false" :loading="loading"></BaseTable>

    <div class="page">
      <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange"
        :current-page="queryAll.startpage" :page-sizes="[10, 15, 20, 25, 30]" :page-size="queryAll.pagesize"
        layout="total, sizes, prev, pager, next, jumper" :total="queryAll.totalNum"></el-pagination>
    </div>
    <!-- 船舶作业报告 -->
    <el-drawer :before-close="handleClose" title="船舶作业报告" :visible.sync="drawerInner" direction="rtl" size="60%">
      <el-form :model="formData" ref="ruleForm" style="padding:10px 20px" label-position="top" size="small">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="船名航次" prop="shipvoyageName" class="top">
              <el-input v-model="formData.shipvoyageName" :disabled="true" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="泊位" prop="berthNo" class="top">
              <el-input v-model="formData.berthNo" :disabled="true" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="贸别" prop="tradeType" class="top">
              <el-input v-model="formData.tradeType" :disabled="true" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="船代" prop="customerName" class="top">
              <el-input v-model="formData.customerName" :disabled="true" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="净吨" prop="netTon" class="top">
              <el-input v-model="formData.netTon" :disabled="true" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="目的港" prop="endPortName" class="top">
              <el-input v-model="formData.endPortName" :disabled="true" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="抵锚时间" prop="arrivalAnchorageTime" class="top">
              <el-input v-model="formData.arrivalAnchorageTime" :disabled="true" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="起锚时间" prop="leaveAnchorageTime" class="top">
              <el-input v-model="formData.leaveAnchorageTime" :disabled="true" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="在锚时间(天)" prop="anchorageDays" class="top">
              <el-input v-model="formData.anchorageDays" :disabled="true" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="靠泊时间" prop="berthTime" class="top">
              <el-input v-model="formData.berthTime" :disabled="true" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="离泊时间" prop="leaveBerthTime" class="top">
              <el-input v-model="formData.leaveBerthTime" :disabled="true" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="停泊时间(天)" prop="berthDays" class="top">
              <el-input v-model="formData.berthDays" :disabled="true" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="非生产性停泊小时(船方原因)" v-if="formData.tradeType == '外贸'">
              <el-input v-model="formData.shipStopHours" :disabled="true" />
            </el-form-item>
            <el-form-item label="非生产性停泊天数(船方原因)" v-else>
              <el-input v-model="formData.shipStopDays" :disabled="true" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="非生产性停泊时间(货方原因)">
              <el-input v-model="formData.cargoStopHours" :disabled="true" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="查询" class="top">
              <el-button size="mini" type="primary" @click="getStopRecord">查询停工记录</el-button>
              <el-button size="mini" type="primary"  v-print="printObj">打印</el-button>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="16">
            <el-form-item label="备注" prop="shipReportRemark" class="top">
              <el-input v-model="formData.shipReportRemark" autocomplete="off"
                :disabled="formData.shipReportStatus == 2 ? true : false" type="textarea" maxlength="500"
                show-word-limit />
            </el-form-item>
          </el-col>
        </el-row>
        <div class="demo-drawer__footer">
          <el-button type="primary" @click="submitInner"
            v-hasPermi="['dispatchDataSubsystem:TShipVoyageController:update']" v-if="formData.shipReportStatus == '1'"
            :loading="ineerLoading" size="small">
            {{ ineerLoading ? "提交中 ..." : "确 认" }}
          </el-button>
          <el-button size="small" @click="drawerInner = false">取消</el-button>
        </div>
      </el-form>
      <!-- 打印布局 -->
<!--      <div style="width: 0;height: 0;overflow: hidden">-->
        <div id="printArea" >
          <table>
            <tr>
              <td colspan="8" style="border: transparent"><h3>唐山曹妃甸文丰码头有限公司船舶作业报告</h3></td>
            </tr>
            <tr>
              <td colspan="8" style="border: transparent;text-align: right"><span>日期:</span></td>
            </tr>
            <tr>
              <td colspan="2">船舶名称</td>
              <td colspan="2">{{formData.shipvoyageName}}</td>
              <td colspan="1">船舶净吨</td>
              <td colspan="3">{{formData.netTon}}</td>
            </tr>
            <tr>
              <td colspan="2">船代</td>
              <td colspan="2">{{formData.customerName}}</td>
              <td colspan="1">货方</td>
              <td colspan="3"></td>
            </tr>
            <tr>
              <td>1</td>
              <td>锚地时间</td>
              <td >{{formData.arrivalAnchorageTime}}</td>
              <td>离锚地时间</td>
              <td >{{formData.leaveAnchorageTime}}</td>
              <td>锚泊时长</td>
              <td >{{formData.anchorageDays}}</td>
              <td ></td>
            </tr>
            <tr>
              <td>2</td>
              <td>靠泊时间</td>
              <td >{{formData.berthTime}}</td>
              <td>离泊时间</td>
              <td >{{formData.leaveBerthTime}}</td>
              <td>停泊时间</td>
              <td >{{formData.berthDays}}</td>
              <td ></td>
            </tr>
            <tr>
              <td >3</td>
              <td >解系缆</td>
              <td colspan="5"></td>
              <td ></td>
            </tr>
            <tr>
              <td >4</td>
              <td >开工时间</td>
              <td colspan="5"></td>
              <td ></td>
            </tr>
            <tr>
              <td >5</td>
              <td >杂作业</td>
              <td colspan="5"></td>
              <td ></td>
            </tr>
            <tr>
              <td >6</td>
              <td >滞港原因及时间</td>
              <td colspan="5"></td>
              <td ></td>
            </tr>
            <tr>
              <td>签字栏</td>
              <td>经办人</td>
              <td ></td>
              <td>审核人</td>
              <td ></td>
              <td>船长/大富</td>
              <td colspan="2" ></td>
            </tr>
          </table>
<!--        </div>-->
      </div>

    </el-drawer>
    <!-- 杂项作业报告 -->
    <el-drawer :before-close="handleClose" :visible.sync="showSundry" direction="rtl" size="60%">
      <template slot="title">
        <div>
          <div>杂项作业报告</div>
          <div style="display: flex;float: right;margin-top: -20px;margin-right: 30px;">
            <el-button style="margin-left: 50px;" size="mini" type="primary" @click="addSundry">添加</el-button>
          </div>
        </div>
      </template>
      <el-form :model="sundryForm" ref="basisRulesRef" size="small">
        <el-table :data="sundryForm.addSundryData" border>
          <el-table-column label="作业内容">
            <template slot-scope="scope">
              <el-form-item :prop="`addSundryData[${scope.$index}].processCode`"
                :rules="[{ required: true, message: '作业内容不能为空' }]">
                <el-select v-model="scope.row.processCode"
                  @change="changeProcessCode(scope.$index, scope.row.processCode)">
                  <el-option v-for="item in processList" :key="item.processCode" :label="item.processName"
                    :value="item.processCode"></el-option>
                </el-select>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="数量">
            <template slot-scope="scope">
              <el-form-item :prop="`addSundryData[${scope.$index}].quantity`"
                :rules="[{ required: true, message: '数量不能为空' }]">
                <el-input-number style="width: 100%;" v-model="scope.row.quantity" :precision="2" :step="0.1"
                  :max="999999"></el-input-number>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="作业日期">
            <template slot-scope="scope">
              <el-form-item :prop="`addSundryData[${scope.$index}].workTime`"
                :rules="[{ required: true, message: '作业日期不能为空' }]">
                <el-date-picker style="width: 100%;" v-model="scope.row.workTime" type="date" placeholder="选择日期">
                </el-date-picker>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-link type="danger"
                @click.native.prevent="deleteCargoInfo(scope.$index, sundryForm.lottingDetailedData)">删除</el-link>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <div class="demo-drawer__footer">
        <el-button type="primary" @click="submitSundry()" :loading="ineerLoading" size="small">
          {{ ineerLoading ? "提交中 ..." : "保 存" }}
        </el-button>
        <el-button size="small" @click="drawerInner = false">取消</el-button>
      </div>
    </el-drawer>
    <!-- 查询停工记录 -->
    <el-dialog title="停工记录" top="10vh" :visible.sync="dialogVisible" width="50%" :before-close="handleClose">
      <BaseTable :data="stopRecordData" :columns="stopRecordColumns" :tableHeight="tableHeight0"
      :pagination="false" :loading="loading"></BaseTable>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="dialogVisible = false">确 定</el-button>
      </span>
    </el-dialog>
</div>
</template>

<script>
import Utils from '@/libs/Utils.js'
import dfilters from '@/libs/Utils.js'
import BaseTable from '@/components/BaseTable'
import api from '@/api/Dispatch/shipJobReport'
import publicapi from '@/api/public'
import headerSearch from '@/components/headerSearch'
export default {
  components: {
    BaseTable,
    headerSearch
  },
  data() {
    return {
      printObj: {
        id: 'printArea',
        popTitle: '页眉', // 打印配置页上方的标题
        extraHead: '', // 最上方的头部文字，附加在head标签上的额外标签，使用逗号分割
        preview: true, // 是否启动预览模式，默认是false
        previewTitle: '打印船舶作业报告', // 打印预览的标题
        previewPrintBtnLabel: '开始打印', // 打印预览的标题下方的按钮文本，点击可进入打印
        zIndex: 20002, // 预览窗口的z-index，默认是20002，最好比默认值更高
        previewBeforeOpenCallback() {
          console.log('正在加载预览窗口！')
        }, // 预览窗口打开之前的callback
        previewOpenCallback() {
          console.log('已经加载完预览窗口，预览打开了！')
        }, // 预览窗口打开时的callback
        beforeOpenCallback() {
          console.log('开始打印之前！')
        }, // 开始打印之前的callback
        openCallback() {
          console.log('执行打印了！')
        }, // 调用打印时的callback
        closeCallback() {
          console.log('关闭了打印工具！')
        }, // 关闭打印的callback(无法区分确认or取消)
        clickMounted() {
          console.log('点击绑定的按钮了！')
        },
        // url: 'http://localhost:8080/', // 打印指定的URL，确保同源策略相同
        // asyncUrl (reslove) {
        //   setTimeout(() => {
        //     reslove('http://localhost:8080/')
        //   }, 2000)
        // },
        standard: '',
        extarCss: ''
      },
      menuFlag: false,
      oldOut: {},
      oldInner: {},
      ineerLoading: false,
      dialogVisible: false,
      tableHeight: window.innerHeight - 200,
      tableHeight0: window.innerHeight - 500,
      // 搜索框显示对象
      selectObject: [
        {
          name: '船名航次',
          type: 'select',
          modelName: 'shipvoyageName',
          selectLabel: 'shipvoyageName',
          selectValue: 'shipvoyageName',
          selectData: []
        },
        {
          name: '船代',
          type: 'select',
          modelName: 'customerId',
          selectLabel: 'customerName',
          selectValue: 'customerId',
          selectData: []
        }
      ],
      // 按钮的list
      buttonList: [
        { label: '船舶作业报告', disabled: false, type: 'primary', icon: 'el-icon-tickets', click: () => this.addDrawerForm, permission: 'dispatchManagement:shipJobReport:ship' },
        { label: '杂项作业报告', disabled: false, type: 'primary', icon: 'el-icon-tickets', click: () => this.addSundryForm, permission: 'dispatchDataSubsystem:dispatch:dispatchInsert' }
      ],
      jobReportColumns: [ // table表头
        { prop: 'shipvoyageName', label: '船名航次' },
        { prop: 'berthNo', label: '泊位' },
        { prop: 'tradeType', label: '贸别' },
        { prop: 'customerName', label: '船代', isShort: true },
        { prop: 'netTon', label: '船舶净重' },
        { prop: 'berthTime', label: '靠泊时间', width: 150 },
        { prop: 'leaveBerthTime', label: '离泊时间', width: 150 },
        { prop: 'berthDays', label: '停泊时间(天)' },
        { prop: 'status', label: '船舶状态' },
        {
          prop: 'shipReportstatus',
          label: '船舶作业报告',
          render: (h, params) => {
            if (params.row.shipReportStatus == '1') {
              return h('el-tag', {
                props: {
                  size: 'mini',
                  type: 'danger'
                },
                domProps: {
                  innerHTML: '未确认'
                }
              })
            }
            return h('el-tag', {
              props: {
                size: 'mini',
                type: 'success'
              },
              domProps: {
                innerHTML: '已确认'
              }
            })
          }
        },
        {
          prop: 'sundryReportStatus',
          label: '杂项作业报告',
          render: (h, params) => {
            if (params.row.sundryReportStatus == '1') {
              return h('el-tag', {
                props: {
                  size: 'mini',
                  type: 'danger'
                },
                domProps: {
                  innerHTML: '未确认'
                }
              })
            }
            return h('el-tag', {
              props: {
                size: 'mini',
                type: 'success'
              },
              domProps: {
                innerHTML: '已确认'
              }
            })
          }
        }
      ],
      stopRecordData: [],
      stopRecordColumns: [
        { prop: 'stopTime', label: '停工时间', width: 270 },
        { prop: 'stopHours', label: '停工时长(小时)' },
        { prop: 'stopName', label: '停工原因' },
        { prop: 'stopTypeName', label: '停工类型' }
      ],
      jobReporttableData: [],
      shipVoyageData: [], // 船名航次数据
      yardList: [],
      customerList: [],
      cargoList: [],
      treeTypeList: [],
      issuingCompanyList: [],
      customerData: [],
      processList: [],
      loading: false,
      queryAll: {
        startpage: 1,
        pagesize: 10,
        totalNum: 0,
        shipvoyageName: '',
        customerCode: ''
      },
      detailsData: null,
      drawerOut: false,
      flagOut: true,
      outForm: {
        portName: '',
        portCode: '',
        logogram: '',
        nationCode: '',
        sortNum: ''
      },
      drawerInner: false,
      formData: {},
      showSundry: false,
      sundryForm: {
        addSundryData: []
      }
    }
  },
  activated() {
    this.getShipvoyage()
    this.getCustomer()
    this.getProcessList()
  },
  methods: {
    /**
     * 获取船名航次
     */
    async getShipvoyage() {
      const res = await publicapi.getListShipvoyage()
      this.shipVoyageData = res.data.data
      this.selectObject[0].selectData = this.shipVoyageData
    },
    /**
   * 获取船代货代
   */
    async getCustomer() {
      await publicapi.getlistCustomer().then(res => {
        if (res.data.code == '0000') {
          this.customerData = res.data.data
          this.selectObject[1].selectData = this.customerData
        }
      })
    },
    /**
     * 获取主作业过程
     */
    async getProcessList() {
      const res = await publicapi.getlistProcess({ mainType: '1' })
      this.processList = res.data.data
    },
    // 获取数据
    async getData() {
      this.loading = true
      await api.getData(this.queryAll).then(res => {
        if (res.status == '200') {
          this.queryAll.startpage = res.data.data.pageNum
          this.queryAll.pagesize = res.data.data.pageSize
          this.queryAll.totalNum = res.data.data.totalNum
          this.jobReporttableData = res.data.data.pages
          this.jobReporttableData.forEach(item => {
            item.berthTime = dfilters.getProcessingDate(item.berthTime, '0')
            item.leaveBerthTime = dfilters.getProcessingDate(item.leaveBerthTime, '0')
          })
          this.loading = false
        }
      })
    },
    /**
     * 船舶作业报告
     */
    async addDrawerForm() {
      if (!this.detailsData) {
        return this.$message.warning('请选择一条数据')
      }
      if (!this.drawerInner) {
        this.drawerInner = true
      }
      await api.getDataById(this.detailsData.id).then(res => {
        if (res.data.code == '0000') {
          if (res.data.data.length == 1) {
            this.formData = res.data.data[0]
          } else if (res.data.data.length > 1) {
            this.formData = res.data.data[0]
            this.formData.cargoStopHours = res.data.data.filter(item => item.stopTypeCode == 'hfyy')[0].shipStopHours
          }
        }
        this.formData.leaveAnchorageTime = dfilters.getProcessingDate(this.formData.leaveAnchorageTime, '0')
        this.formData.arrivalAnchorageTime = dfilters.getProcessingDate(this.formData.arrivalAnchorageTime, '0')
        this.formData.berthTime = dfilters.getProcessingDate(this.formData.berthTime, '0')
        this.formData.leaveBerthTime = dfilters.getProcessingDate(this.formData.leaveBerthTime, '0')
      })
    },
    // 选中数据
    selectDataList(val) {
      this.detailsData = null
      this.detailsData = val
      this.buttonList.forEach(msg => {
        if (this.detailsData.status !== '离泊') {
          msg.disabled = true
        } else {
          msg.disabled = false
        }
      })
      this.formData = this.$options.data().formData;
    },
    // 删除
    deleteCargoInfo(index, rows) {
      this.$confirm('是否删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        rows.splice(index, 1);
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    /**
     * 新建、编辑保存
     */
    submitInner() {
      const form = {
        id: this.formData.id,
        shipReportStatus: '2',
        anchorageDays: this.formData.anchorageDays,
        berthDays: this.formData.berthDays,
        cargoStopHours: this.formData.cargoStopHours,
        shipStopDays: this.formData.shipStopDays,
        shipStopHours: this.formData.shipStopHours,
        shipReportRemark: this.formData.shipReportRemark
      }
      api.dataUpdate(form).then(res => {
        if (res.data.code == '0000') {
          this.$message.success(res.data.msg)
          this.drawerInner = false
          this.getData()
          this.detailsData = null
        }
      })
    },
    // 查询停工记录
    async getStopRecord() {
      if (!this.dialogVisible) {
        this.dialogVisible = true
      }
      await api.getStopRecord(this.detailsData.id).then(res => {
        if (res.data.code == '0000') {
          this.stopRecordData = res.data.data
        }
      })
    },
    // 杂项作业报告
    async addSundryForm() {
      if (!this.detailsData) {
        return this.$message.warning('请选择一条数据')
      }
      if (!this.showSundry) {
        this.showSundry = true
      }
      await api.getSundryDataById(this.detailsData.id).then(res => {
        if (res.data.code == '0000') {
          if (res.data.data.length == 1) {
            this.formData = res.data.data[0]
          } else if (res.data.data.length > 1) {
            this.formData = res.data.data[0]
            this.formData.cargoStopHours = res.data.data.filter(item => item.stopTypeCode == 'hfyy')[0].shipStopHours
          }
        }
        this.formData.leaveAnchorageTime = dfilters.getProcessingDate(this.formData.leaveAnchorageTime, '0')
        this.formData.arrivalAnchorageTime = dfilters.getProcessingDate(this.formData.arrivalAnchorageTime, '0')
        this.formData.berthTime = dfilters.getProcessingDate(this.formData.berthTime, '0')
        this.formData.leaveBerthTime = dfilters.getProcessingDate(this.formData.leaveBerthTime, '0')
      })
    },
    // 添加按钮
    addSundry() {
      const data = {
        id: this.detailsData.id,
        processCode: '',
        processName: '',
        quantity: '',
        workTime: ''
      }
      this.sundryForm.addSundryData.push(data)
    },
    changeProcessCode(index, row) {
      this.sundryForm.addSundryData[index].processName = this.processList.filter(item => item.processCode == row)[0].processName
    },
    // 保存杂项作业报告
    submitSundry() {
      api.saveSundryDataById({ shipvoyageId: this.detailsData.id }).then(res => {
        if (res.data.code == '0000') {
          this.$message.success(res.data.msg)
          this.showSundry = false
          this.getData()
          this.detailsData = null
        }
      })
    },
    searchClick(searchData) {
      this.queryAll.startpage = 1
      this.queryAll = Object.assign(this.queryAll, searchData)
      this.detailsData = null
      this.getData()
    },
    handleSizeChange(val) {
      this.queryAll.pagesize = val
      this.getData()
    },
    handleCurrentChange(val) {
      this.queryAll.startpage = val
      this.getData()
    },
    handleClose(done) {
      let oldV = {}
      let newV = {}
      if (this.showSundry) {
        oldV = this.oldOut
        newV = this.outForm
      }
      if (this.drawerInner) {
        oldV = this.oldInner
        newV = this.innerForm
      }
      if (!Utils.compareData(oldV, newV)) {
        this.$confirm('确定是否关闭？')
          .then(_ => {
            done()
          })
          .catch(_ => { })
      } else {
        done()
      }
    }
  }
}
</script>

<style lang="less" scoped>
.selectBox {
  justify-content: space-between;
  display: flex;
  background: #ffffff;
  border: 1px solid #e1e4eb;
  border-bottom: 0;
  border-left: none;
  height: 50px;
  position: relative;
  align-items: center;
  padding-left: 14px;
  padding-right: 20px;
}

.input_box {
  display: flex;
}

.page {
  background: #ffffff;
  text-align: right;
  border-radius: 0 0 4px 4px;
  padding: 5px 20px;
}

/deep/.el-tabs--border-card>.el-tabs__content {
  padding: 0 !important;
}

//抽屉底部样式
/deep/ .el-drawer__header {
  margin-bottom: 0;
  padding: 16px;
  border-bottom: 1px solid gainsboro;
}

.demo-drawer__footer {
  text-align: right;
  padding-right: 20px;
  border-top: 1px solid #c8cfde;
  background-color: #f5f7fa;
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  line-height: 50px;
}

.box {
  background: #ffffff;
  border: 1px solid #e1e4eb;
  border-radius: 4px 4px 0 0;
  border-top: none;
}

.el-form-item--small.el-form-item {
  margin-bottom: 0px;
}
/*@media print {
  .hidden{
    display: block;
  }
}*/
/*@page {
  size: auto;
  margin: 0mm;
}*/
table,
table tr th,
table tr td {
  border: 1px solid #111010ed;
  text-align: center;
  height: 20px;
}

table {
  width: 100%;
  border-collapse: collapse;
  table-layout: fixed;
  font-size: 15px;
}
</style>
